package com.yunmasoft.service.pay.alipay;

import com.common.util.RedisHelper;
import com.common.util.ReflectHWUtils;
import com.common.util.SystemHWUtil;
import com.google.common.eventbus.EventBus;
import com.house.ujiayigou.thirdpart.alipay.config.AlipayConfig;
import com.string.widget.util.ValueWidget;
import com.time.util.TimeHWUtil;
import oa.entity.AlipayNotifySuccess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Service("service")
public class PayService implements PayOperation {

    /***
     "payType": //支付方式 1-畅捷支付，2-支付宝 3-畅捷担保支付 4-支付宝担保支付 100-激活码支付 101-线下支付
     */
    public static final int PAYTYPE_CHANPAY = 1;
    public static final int PAYTYPE_ALIPAY = 2;


    public static final int PAYTYPE_MONIPAY = 101;


    /***
     * 存储订单的支付结果:store_pay_result
     */
    public static final String REDIS_KEY_STORE_ORDER_PAY_RESULT = "store_pay_result";
    /***
     * 订单支付时间
     */
    public static final String REDIS_KEY_STORE_ORDER_PAY_TIME = "store_pay_time";
    public static final String ORDER_PAY_SUCCESS_LABEL = "success";
    protected final Logger logger = LoggerFactory.getLogger("com/yunmasoft/service/pay");
    /*@Resource
    private AlipayNotifySuccessDao alipayNotifySuccessDao;*/
    @Resource
    private EventBus eventBus;

    public PayService() {
    }

    /***
     * 支付成功之后,进行标记<br >
     *     必须在确认订单成功之后调用
     */
    public static void setPaySuccessTag(String orderNo) {
        RedisHelper.getInstance().saveExpxKeyCache("store_" + orderNo + "_payResult", ORDER_PAY_SUCCESS_LABEL, 60 * 60 * 12);//过期时间为 12小时
    }

    /***
     * 通过redis 缓存判断订单是否支付成功
     * @param orderNo
     * @return
     */
    public static boolean isPaySuccess(String orderNo) {
        String payResult = RedisHelper.getInstance().getCache("store_" + orderNo + "_payResult");
        return ORDER_PAY_SUCCESS_LABEL.equals(payResult);
    }

    public String verify(Map<String, String> params) {
        return null;
    }

    public String preparePostRequest(com.house.ujiayigou.thirdpart.alipay.info.PayFormInfo payFormInfo) {
        return null;
    }

    public String payNotify(String out_trade_no, String trade_no, String trade_status, Map<String, String> params) {
        return null;
    }

   /* public boolean getPaymentResult(String userid, String orderid) {
        String payResult = RedisHelper.getInstance().getKeyCache(PayService.REDIS_KEY_STORE_ORDER_PAY_RESULT, orderid);
        return PayService.ORDER_PAY_SUCCESS_LABEL.equalsIgnoreCase(payResult);
    }
*/

    protected String PaymentNotifyhandler(String out_trade_no, String trade_no, Map<String, String> params, int payMethod, String sellerAccount) {

//        String currentCache = RedisHelper.getInstance().getKeyCache(Constant.REDIS_ID_STORE, out_trade_no) + "<br>";
//        RedisHelper.getInstance().saveKeyCacheAndExpire(Constant.REDIS_ID_STORE, out_trade_no, currentCache + "OnNotify"+out_trade_no);

        BigDecimal price = null;

        if (params.containsKey("total_amount")) {
            price = new BigDecimal(params.get("total_amount"));
        } else {
            price = new BigDecimal("0.00");
        }

        if (params.containsKey("total_fee")) {
            price = new BigDecimal(params.get("total_fee"));
        }

        String buyer_email = (params.get("buyer_logon_id") == null ? SystemHWUtil.EMPTY : params.get("buyer_logon_id").toString());
        String buyer_id = (params.get("buyer_id") == null ? SystemHWUtil.EMPTY : params.get("buyer_id").toString());
        String userIdAndLoginnameAndOrgId = null;
        String random_id = null;
        if (params.containsKey("extra_common_param")) {
            String temp = params.get("extra_common_param").toString();
            String[] extra_common_paramArr = temp.split("::");
            random_id = extra_common_paramArr[1];

            if (extra_common_paramArr.length > 2) {
                userIdAndLoginnameAndOrgId = extra_common_paramArr[2];
            }
            logger.error("userIdAndLoginnameAndOrgId:" + userIdAndLoginnameAndOrgId);
            if (ValueWidget.isNullOrEmpty(buyer_id) && !ValueWidget.isNullOrEmpty(userIdAndLoginnameAndOrgId)) {
                buyer_id = userIdAndLoginnameAndOrgId.split("_", 3)[1];
            }
        }
        if (ValueWidget.isNullOrEmpty(random_id)) {
            random_id = params.get("body");
        }

//        currentCache = RedisHelper.getInstance().getKeyCache(Constant.REDIS_ID_STORE, out_trade_no) + "<br>";
//        RedisHelper.getInstance().saveKeyCacheAndExpire(Constant.REDIS_ID_STORE, out_trade_no, currentCache);


//        if (cnt == 1) {

//            String access_token = getAccessTokenByRandomId(random_id);

        java.text.DateFormat format1 = new java.text.SimpleDateFormat(TimeHWUtil.yyyyMMddHHmmss);
        String dateString = format1.format(new Date());

        String coupon = null;
            /*if (Constant.useDebugCouponValue) {
                coupon = Constant.couponValue.toString();
//                    coupon = new BigDecimal(price.floatValue() + ).toString();
            } else {*/
        coupon = "0.00";
//            }

        BigDecimal totalPrice = new BigDecimal(coupon).add(price);

        String totalPriceStr = ValueWidget.formatBigDecimal(totalPrice);

        if (ValueWidget.isNullOrEmpty(sellerAccount)) {
            sellerAccount = AlipayConfig.MY_EMAIL;
        }
        if (ValueWidget.isNullOrEmpty(buyer_email)) {
            buyer_email = buyer_id;
        }
        /*if(BaseController.isPayDebug()) {
            String commitJson = BaseController.getCommitOrderJson(out_trade_no);
            //确认订单有两块,一个是这里,一个是com/chanjet/gov/controller/weixin/WeixinPayController.java中的 notify 方法
            if (null != commitJson) {
                ConfirmOrderRespDto confirmOrderRespDto = JSONExtension.parseObject(commitJson, ConfirmOrderRespDto.class);
                totalPriceStr = ValueWidget.formatBigDecimal(confirmOrderRespDto.getPayTotal());
            }
        }*/
        RedisHelper.getInstance().saveKeyCache(PayService.REDIS_KEY_STORE_ORDER_PAY_RESULT, out_trade_no, PayService.ORDER_PAY_SUCCESS_LABEL);
        //TODO 确认订单 添加业务代码
        /*BaseResponseDto baseResponseDto = orderBusiness.confirmOrderPayV2( out_trade_no, trade_no, buyer_email, buyer_id, "畅捷通",
                sellerAccount, dateString, totalPriceStr, "userIdAndLoginnameAndOrgId:" + userIdAndLoginnameAndOrgId, payMethod, random_id);
        if (baseResponseDto.result) {
            setPaySuccessTag(out_trade_no);//支付成功
        } else {
            logger.error("confirm order failed:" + out_trade_no);
            String resultJson = baseResponseDto.toJson();
            logger.error(out_trade_no + ":" + resultJson);
            String paramsStr = params.toString();
            logger.error(paramsStr);
//            currentCache = RedisHelper.getInstance().getKeyCache(Constant.REDIS_ID_STORE, out_trade_no) + "<br>";
//            RedisHelper.getInstance().saveKeyCacheAndExpire(Constant.REDIS_ID_STORE, out_trade_no, currentCache + ",confirm order failed:" + resultJson + ",params:" + paramsStr);
        }*/
//        RedisHelper.getInstance().saveExpxKeyCache("alipayresult_"+out_trade_no, ORDER_PAY_SUCCESS_LABEL,60*5);//5分钟,目的是为了大数据埋点统计支付宝支付成功
        AlipayNotifySuccess alipayNotifySuccess = new AlipayNotifySuccess();
        ReflectHWUtils.setObjectValue(alipayNotifySuccess, params);
        try {
            paySuccessCallback(alipayNotifySuccess);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("paySuccessCallback error", e);
            //straintViolationException: Duplicate entry '2018021021001004230291722859' for key 'unique_key222'
            if (e.getMessage().contains("could not execute statement")) {
                alipayNotifySuccess.setTrade_no(alipayNotifySuccess.getTrade_no() + "_1");
                paySuccessCallback(alipayNotifySuccess);
            }
        }
        return ORDER_PAY_SUCCESS_LABEL;
    }

    /***
     * 支付成功后的逻辑统一放在如下方法中
     * @param alipayNotifySuccess
     */
    protected void paySuccessCallback(AlipayNotifySuccess alipayNotifySuccess) {
        System.out.println("支付成功,支付人 :" + alipayNotifySuccess.getBuyer_logon_id());
        setPaySuccessTag(alipayNotifySuccess.getOut_trade_no());
        //1. 保存到数据库
//        this.alipayNotifySuccessDao.add(alipayNotifySuccess);
        this.eventBus.post(alipayNotifySuccess);
    }

    public Integer getPayType() {
        return 1;
    }

}
